/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import { hvigorCore } from '@ohos/hvigor';

import { ProjectModel } from '../model/project/project-model.js';
import { ProjectBuildProfile } from '../options/build/project-build-profile.js';
import { Named } from '../options/options.js';
import { getElementFromArr } from '../utils/array-util.js';
import { OhosLogger } from '../utils/log/ohos-logger.js';

const _log = OhosLogger.getLogger('find-target-product');

/**
 * 根据命令行中的配置找到根项目下的build-profile.json5中的Product
 *
 * @param projectModuleModel
 */
export function findTargetProduct(projectModuleModel: ProjectModel): ProjectBuildProfile.ProductBuildOpt {
  const targetProduct = getCurrentProductName();

  // 检查app中是否有该product
  const mProduct: Named | undefined = getElementFromArr(projectModuleModel.getProfileOpt().app.products, targetProduct);
  if (!mProduct) {
    _log.printErrorExit(
      'PRODUCT_NAME_NO_FOUND',
      [targetProduct, projectModuleModel.getName(), projectModuleModel.getProfilePath()]
    );
  }
  return mProduct as ProjectBuildProfile.ProductBuildOpt;
}

/**
 * 从命令行获取productName
 */
export function getCurrentProductName(): string {
  const configProduct = hvigorCore.getExtraConfig().get('product');
  // 没有配置时默认是default
  return configProduct ? configProduct : 'default';
}